import java.util.PriorityQueue;

class MyTimerTask implements Comparable<MyTimerTask>{
    private Runnable task;
    private long time;

    public MyTimerTask(Runnable task, long time) {
        this.task = task;
        this.time = time;

    }

    @Override
    public int compareTo(MyTimerTask o) {
        return (int)(this.time-o.time);
    }
    public long getTime(){
        return time;
    }
    public void run(){
        task.run();
    }
}
class MyTimer {
    private PriorityQueue<MyTimerTask> queue = new PriorityQueue<>();
    private Object locker = new Object();
    public void schedule(Runnable task,long delay){
        synchronized (locker){
            MyTimerTask timerTask = new MyTimerTask(task,System.currentTimeMillis()+delay);
            queue.offer(timerTask);
            locker.notify();
        }
    }

    public MyTimer() {
        Thread t = new Thread(()->{
            try{
                while (true){
                    synchronized (locker){
                        while (queue.isEmpty()){
                            locker.wait();
                        }
                        MyTimerTask task =queue.peek();
                        if(task.getTime()>System.currentTimeMillis()){
                            locker.wait(task.getTime()-System.currentTimeMillis());
                        }else {
                            task.run();
                            queue.poll();
                        }
                    }
                }
            }catch (InterruptedException e){
                throw new RuntimeException(e);
            }

        });
        t.start();
    }
}
public class Demo5 {

}
